<?php

	/**
	 * @see Zend_Db_Select
	 */
	require_once 'Zend/Db/Select.php';
	
	
	class Bike_Db_Select extends Zend_Db_Select
	{		const CALC_FOUND_ROWS 		= 'calcfoundrows';
		const SQL_CALC_FOUND_ROWS   = 'SQL_CALC_FOUND_ROWS';
		
		/**
		 * The initial values for the DISTINCT part.
		 *
		 * @var array
		 */
		protected static $_distinctParts = array(
			self::DISTINCT     		=> self::SQL_DISTINCT,
			self::CALC_FOUND_ROWS 	=> self::SQL_CALC_FOUND_ROWS,
		);
		
		static public function getDistinctParts()
		{
			return self::$_distinctParts;
		}		
		
		protected function _renderColumns($sql)
	    {
	        $symbol = $this->getAdapter()->getQuoteIdentifierSymbol();
	        foreach($this->_parts[self::COLUMNS] as $n => $columnEntry)
	        {	        	$alias = $columnEntry[2];
	        	if(substr($alias, 0, 1) == $symbol)
	        	{	      			$matches = array();
	      			if(preg_match("/^[".$symbol."]+([\w]{1}[_\w\d]+)[".$symbol."]+$/s", $alias, $matches))
	      			{	      				$this->_parts[self::COLUMNS][$n][2] = $matches[1];
	      			}
	        	}
	        }
	        return parent::_renderColumns($sql);
	    }
	    
	    protected function _checkDistinct()
	    {
	    	if(!is_array($this->_parts[self::DISTINCT]))
	    	{
	    		$this->_parts[self::DISTINCT] = array();
	    	}
	    }
	    
	    /**
	     * Makes the query SELECT DISTINCT.
	     *
	     * @param bool $flag Whether or not the SELECT is DISTINCT (default true).
	     * @return Zend_Db_Select This Zend_Db_Select object.
	     */
	    public function distinct($flag = true)
	    {
	    	$this->_checkDistinct();
	    	$this->_parts[self::DISTINCT][self::DISTINCT] = (bool) $flag;
	    	return $this;
	    }
	    
	    /**
	     * Makes the query SELECT SQL_CALC_FOUND_ROWS.
	     *
	     * @param bool $flag Whether or not the SELECT is SQL_CALC_FOUND_ROWS (default true).
	     * @return Zend_Db_Select This Zend_Db_Select object.
	     */
	    public function calcFoundRows($flag = true)
	    {
	    	$this->_checkDistinct();
	    	$this->_parts[self::DISTINCT][self::CALC_FOUND_ROWS] = (bool) $flag;
	    	return $this;
	    }
	    
	    /**
	     * Render DISTINCT clause
	     *
	     * @param string   $sql SQL query
	     * @return string
	     */
	    protected function _renderDistinct($sql)
	    {
	    	foreach($this->getDistinctParts() as $key => $value)
	    	{
	    		if(isset($this->_parts[self::DISTINCT][$key]) && $this->_parts[self::DISTINCT][$key])
	    		{
	    			$sql .= ' ' . $value;
	    		}
	    	}
	    		    
	    	return $sql;
	    }
	}